import { UdModal, http, IUdFormItem } from "@/lib"
import React from "react"
import { message } from "antd"
import SettledReviewModal from "@/components/SettledReviewModal"
import apis from "@/apis"
import _ from "lodash"

export const todoApproveModalOpen = ({ data, successSubmit, reviewBeforeRequest, modalItems, approveBeforeHandle, passUrl }: IsettledReviewOpenModal) => {
  const userId = JSON.parse(sessionStorage.getItem('UaaSysInfo'))?.profile?.id
  let uploadFiles = []
  const updateFiles = (files) => {
    uploadFiles = files
  }
  UdModal.open({
    title: '审批',
    content: <SettledReviewModal updateFiles={updateFiles} items={modalItems} />,
    onOk: (values) => {
      const { taskId, roles: roleIds, tableData } = data
      const { files, isValid, ...reset } = values
      // url和type必传，type固定'url'
      const attachments = uploadFiles?.map(({ url, name }) => ({ url, name, type: 'url' }))
      const params = { ...reset, taskId, userId, attachments, roleIds, quotaModifyHistoryRespVos: tableData }
      let url = passUrl || apis.TodoApprovePass
      if (isValid == 1) {
        // 不通过
        url = apis.SettledReviewReturn
        delete params.quotaModifyHistoryRespVos
      }
      if (approveBeforeHandle && _.isFunction(approveBeforeHandle)) {
        approveBeforeHandle(params)
      }
      if (reviewBeforeRequest && _.isFunction(reviewBeforeRequest)) {
        // 需要在提交审批流前进行额外请求
        return new Promise((resolve, reject) => {
          reviewBeforeRequest().then(res => {
            return http.post(url, params).then(res => {
              message.success('操作成功')
              resolve()
              successSubmit && successSubmit()
            })
          }).catch(() => reject())
        })
      } else {
        return http.post(url, params).then(res => {
          message.success('操作成功')
          successSubmit && successSubmit()
        })
      }
    }
  })
}

interface IsettledReviewOpenModal {
  data: any
  successSubmit?: () => void
  reviewBeforeRequest?: () => Promise<any>
  modalItems?: IUdFormItem[]
  approveBeforeHandle?: (params) => void
  passUrl?: string
}
